<?php
$isReloadable = true;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

if (reqVarInt('sd')==0) {
	$sqlSel = "SELECT id_set_dati "
			." FROM rgl_bilancio "
			." WHERE id_bil = ".reqVarInt('bil1');
	$objDB->query($sqlSel,'selRecDato');
	if (!$acRec = $objDB->fetch('selRecDato')) {
		backOnErr("calDato - bil1. '".reqVar('bil1')."' mancante o errato");
	}
	$_REQUEST['sd'] = $acRec['id_set_dati'];
}
$idSetDati = reqVarInt('sd');
$sqlSel = "SELECT d.*, sd.cod_set_dati, sd.descr AS sd_descr "
		." FROM rgl_def_dato d "
		." INNER JOIN rgl_set_dati sd ON sd.id_set_dati = d.id_set_dati"
				." WHERE d.cod_dato = '".reqVarAS('cd')."' AND d.id_set_dati = ".$idSetDati;
$objDB->query($sqlSel,'selRecDato');
if (!$acRec = $objDB->fetch('selRecDato')) {
	backOnErr("var. cd. '".reqVar('cd')."' mancante o errato");
}
$sCalc='';
switch(reqVar('azione')) {
	case 'chgB1':
		$_REQUEST['bil2']='';
	case 'chgB2':
		$_REQUEST['bil3']='';
}
$aVar = array();
if (reqVarInt('bil2') > 0) {
	$msgPag = calcDato($acRec, $aVar, $sCalc);
}

$_REQUEST = array_merge($acRec,$_REQUEST);

$sqlSel = "SELECT id_bil,data_rif,descr, id_azienda FROM rgl_bilancio "
	." WHERE id_set_dati = ".$idSetDati
	." ORDER BY id_bil DESC LIMIT 0,20";
$objDB->query($sqlSel,'selRec');
$aBil1 = array(''=>'-- seleziona un bilancio');
$aDataRif = '';
$idAzienda = 0;
while($acX = $objDB->fetch('selRec')) {
	$aBil1[$acX['id_bil']] = $acX['id_azienda']." - ".YMD2DMY($acX['data_rif'])
		." - ".$acX['descr'];
	if (reqVarInt('bil1') == $acX['id_bil']) {
		$dataRif = $acX['data_rif'];
		$idAzienda = $acX['id_azienda'];
	}
}
if (reqVar('bil1')>0) {
	$sqlSel = "SELECT id_bil,data_rif,descr, id_azienda FROM rgl_bilancio "
		." WHERE data_rif < '".$dataRif."' AND id_azienda = ".$idAzienda
		."    AND id_set_dati = ".$idSetDati
		." ORDER BY data_rif DESC, id_bil DESC ";
	$objDB->query($sqlSel,'selRec');
	$aBil2 = array(''=>'-- seleziona un bilancio');
	while($acX = $objDB->fetch('selRec')) {
		$aBil2[$acX['id_bil']] = $acX['id_azienda']." - ".YMD2DMY($acX['data_rif'])
			." - ".$acX['descr'];
	}
}

$sCmdR = "";
if (reqVarInt('bil2') > 0) {
	$sCmdR .= "<a class='cmd1' href=\"javascript:submAz('calcDato');\">ricalcola</a>";
}
$sCmdR .=  cmdTorna('torna'); 

$aOpzTesta['aMenuVar']['bilancio CEE']
	['href'] = "bilCeeVis.php?id=".reqVarInt('bil1')."&idp=".reqVarInt('bil2');
if (reqVarInt('bil2')>0) {
	$aOpzTesta['aMenuVar']['bilancio riclassificato']
		['href'] = "bilRicVis.php?id=".reqVarInt('bil1')."&idp=".reqVarInt('bil2');
	$aOpzTesta['aMenuVar']['rendiconto finanziario']
		['href'] = "renFinVis.php?id=".reqVarInt('bil1')."&idp=".reqVarInt('bil2');
	$aOpzTesta['aMenuVar']['indici']
		['href'] = "indiciVis.php?id=".reqVarInt('bil1')."&idp=".reqVarInt('bil2');
}
testaHtml('',$msgPag,'ratg',$aOpzTesta);
?>
<script type="text/javascript">
<!--
function confEli() {
	if (confirm("Confermi ?")) {
		document.location.href = "datoMod.php?azione=elimina&cd=<?=reqVar('cd')?>&xsn=<?=XSN?>";
	}
}
function submAz(az) {
	document.frm1.azione.value = az;
	document.frm1.submit();
}
//-->
</script>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
         <? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm('frm1','',array('enctype'=>true));
echo getHtmlHidden('azione','salva');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('sd');
echo getHtmlHidden('cd');
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Definizione Dato</td>
   </tr>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Set dati</td>
		<td class='txt1' colspan='3'>
			<?=getHtmlVisCode('cod_set_dati')?>
		</td>
		<td class='txt1' colspan='14'>
			<?=getHtmlVisText('sd_descr')?>
		</td>
	</tr>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Codice</td>
		<td class='txt1' colspan='3'>
			<?=getHtmlVisCode('cod_dato')?>
		</td>
		<td class='lab1' colspan='3' valign='top'>Padre</td>
		<td class='txt1' colspan='11'>
			<?=getHtmlVisCode('cod_dato_padre')?>
		</td>
	</tr>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Descrizione</td>
		<td class='txt1' colspan='11'>
			<?=getHtmlVisText('descr')?>
		</td>
		<td class='lab1' colspan='2' valign='top'>Valore</td>
		<td class='txt1' colspan='4' align='right'>
			<?
			if ($acRec['tipo_tab_dati']==1) {
				$varName = 'B_'.$acRec['cod_dato'];
			} else {
				$varName = 'Q_'.$acRec['cod_dato'];
			}		
			switch($acRec['tipo_valore']) {
				case 'euro':
					echo number_format((double)rglVx($aVar,$varName),2,',','.');
					break;
				case 'num':
					echo number_format((double)rglVx($aVar,$varName),0,',','.');
					break;
				case 'perc':
					echo number_format((double)rglVx($aVar,$varName),3,',','.')."%";
					break;
				default:
					echo $aVar[$varName];
			}
			?>&nbsp;
		</td>
	</tr>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Cod. sezione</td>
		<td class='txt1' colspan='7'>
			<?=getHtmlVisText('cod_sez')?>
		</td>
		<td class='lab1' colspan='3' valign='top'>Cod. fonte</td>
		<td class='txt1' colspan='7'>
			<?=getHtmlVisText('cod_fonte')?>
		</td>
	</tr>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Tipo valore</td>
		<td class='txt1' colspan='3'>
			<?=getHtmlVisText('tipo_valore')?>
		</td>
		<td class='lab1' colspan='3' valign='top'>
			<?echo ($acRec['tipo_tab_dati']==1)?'Modalita\' quadratura':'Modalita\' calcolo';?>
		</td>
		<td class='txt1' colspan='11'>
			<?
			switch($acRec['flag_quad_calc']) {
				case 'totsub':
					echo 'Totale sottovoci';
					break;
				case 'calc':
					echo 'Script';
					break;
				case 'totmax':
					echo 'Massimo totale sottovoci';
					break;
				default:
					echo $acRec['flag_quad_calc'];
			}			
			?>
		</td>
	</tr>
<?
if (reqVarTrim('script')!='') {
?>
	<tr>
		<td class='lab1' colspan='3' valign='top'>Script</td>
		<td class='txt1' colspan='17'>
			<?=getHtmlVisNote('script')?>
		</td>
	</tr>
<?
}
?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Elemeti di Calcolo del Dato</td>
   </tr>
<?/*//////////////////////////////////////////////////
   <tr>
      <td class="lab1" align="left" colspan='3'>Tab.bil.ric.</td>
      <td class="txt1" align="left" colspan='17'>
         <?echo getHtmlSelect('id_def_tdati_bilric',$aTDBR,'@REQ',array("onChange"=>"document.frm1.submit();"));?>
      </td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Tab.ren.fin.</td>
      <td class="txt1" align="left" colspan='17'>
         <?echo getHtmlSelect('id_def_tdati_renfin',$aTDRF,'@REQ',array("onChange"=>"document.frm1.submit();"));?>
      </td>
   </tr>
   <tr>
      <td class="lab1" align="left" colspan='3'>Tab.indici</td>
      <td class="txt1" align="left" colspan='17'>
         <?echo getHtmlSelect('id_def_tdati_indici',$aTDIN,'@REQ',array("onChange"=>"document.frm1.submit();"));?>
      </td>
   </tr>
//*/////////////////////////////////////?>
   <tr>
      <td class="lab1" colspan='3' align='left'>Bilancio rif. </td>
      <td class="txt1" colspan='17' align='left'>
      	<? 
      	$aOptChgB1 = array("onChange"=>"submAz('chgB1');");
      	echo getHtmlSelect('bil1',$aBil1,'@REQ',$aOptChgB1);?>
      </td>
   </tr>
<?
	$aOptChgB2 = array("onChange"=>"submAz('chgB2');");
	if (reqVar('bil1') > 0) {
?>
   <tr>
      <td class="lab1" colspan='3' align='left'>Bilancio prec. </td>
      <td class="txt1" colspan='17' align='left'>
      	<? echo getHtmlSelect('bil2',$aBil2,'@REQ',$aOptChgB2);?>
      </td>
   </tr>
<?
	}
echo $sCalc;
?>
</table>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="right">
         <? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";
codaHtml();
exit();

function calcDato($acRec, &$aVar, &$sCalc) {
	global $objDB,$objSess;
	$msg = '';
	$aVar = array();
	$aDefDati = array();
	$msg = aVarCalcTabDati(reqVarInt('bil1'), reqVarInt('bil2'), $aVar, $aDefDati, 99);
	//dbg_($aVar);
	if ($msg!='') {
		return $msg;
	}
	
	if ($acRec['flag_quad_calc'] == 'totsub') {
		return calcDatoTotSub($acRec, $aVar, $sCalc);
	}
	
	if (trim($acRec['script'])=='') {
		$sCalc = '';
		zzDatiRef($acRec, $aVar, $sCalc);
		return '';
	}
	
	return calcDatoScript($acRec, $aVar, $sCalc);
}

function calcDatoScript($acRec, &$aVar, &$sCalc) {
	global $objDB,$objSess;

	$objParse = new rglParser;
	if(!$objParse->parse($acRec['script'])) {
		return $objParse->getError();
	}
	//dbg_("objParse->aVariables: ".print_r($objParse->aVariables,1));
	$sCalc = '';
	$sCalc .= "<tr>\n<td class='lab1' colspan='20' align='center'><b>Dati utilizzati nel calcolo</b></td>\n</tr>\n";
	$sCalc .= "<tr>\n"
		."<td class='lab1' colspan='4' align='center'>Nome</td>\n"
		."<td class='lab1' colspan='10' align='center'>Descrizione</td>\n"
		."<td class='lab1' colspan='6' align='center'>Valore</td>\n"
		."</tr>\n";
	if ($acRec['tipo_tab_dati']==1) {
		$varName = 'B_'.$acRec['cod_dato'];
	} else {
		$varName = 'Q_'.$acRec['cod_dato'];
	}
	if (isset($objParse->aVariables[$varName])) {
		unset($objParse->aVariables[$varName]);
	}
	foreach($objParse->aVariables as $varName => $aPropVar) {
		$codX = substr($varName,2);
		$sSql = "SELECT descr,tipo_valore FROM rgl_def_dato "
			." WHERE cod_dato = '".addslashes($codX)."' "
			."    AND id_set_dati = ".$acRec['id_set_dati'];
		$objDB->query($sSql);
		$aX = $objDB->fetch();
		switch($aX['tipo_valore']) {
			case 'euro':
				$sVal = number_format((double)rglVx($aVar,$varName),2,',','.');
				break;
			case 'num':
				$sVal = number_format((double)rglVx($aVar,$varName),0,',','.');
				break;
			case 'perc':
				$sVal = number_format((double)rglVx($aVar,$varName),3,',','.')."%";
				break;
			default:
				$sVal = rglVx($aVar,$varName);
		}	
		$sCalc .= "<tr>\n"
			."<td class='txt1' colspan='4' align='left'>"
			."<a href='calcDato.php?cd=$codX&bil1=".reqVar('bil1')."&bil2=".reqVar('bil2')."&xsn=".XSN
			."' class='txt1'>$varName</a></td>\n"
			."<td class='txt1' colspan='10' align='left'>".rglVx($aX,'descr')."</td>\n"
			."<td class='txt1' colspan='6' align='right'>".$sVal."&nbsp;</td>\n"
			."</tr>\n";
	}
	zzDatiRef($acRec, $aVar, $sCalc);
	return '';

}

function calcDatoTotSub($acRec, &$aVar, &$sCalc) {
	global $objDB,$objSess;
		$sCalc = '';
		$sCalc .= "<tr>\n<td class='lab1' colspan='20' align='center'><b>Sottovoci</b></td>\n</tr>\n";
		$sCalc .= "<tr>\n"
			."<td class='lab1' colspan='4' align='center'>Nome</td>\n"
			."<td class='lab1' colspan='10' align='center'>Descrizione</td>\n"
			."<td class='lab1' colspan='6' align='center'>Valore</td>\n"
			."</tr>\n";
		$sSql = "SELECT d.cod_dato, d.descr, d.tipo_valore "
			." FROM rgl_def_dato d "
			." WHERE d.cod_dato_padre = '".reqVarAS('cd')."'"
			."    AND d.id_set_dati = ".$acRec['id_set_dati'];;
		$objDB->query($sSql);
		while($aX = $objDB->fetch()) {
			$codX = $aX['cod_dato'];
			if ($aX['tipo_tab_dati']==1) {
				$varName = 'B_'.$codX;
			} else {
				$varName = 'Q_'.$codX;
			}
			switch($aX['tipo_valore']) {
				case 'euro':
					$sVal = number_format((double)rglVx($aVar,$varName),2,',','.');
					break;
				case 'num':
					$sVal = number_format((double)rglVx($aVar,$varName),0,',','.');
					break;
				case 'perc':
					$sVal = number_format((double)rglVx($aVar,$varName),3,',','.')."%";
					break;
				default:
					$sVal = rglVx($aVar,$varName);
			}	
			$sCalc .= "<tr>\n"
				."<td class='txt1' colspan='4' align='left'>"
				."<a href='calcDato.php?cd=$codX&bil1=".reqVar('bil1')."&bil2=".reqVar('bil2')."&xsn=".XSN
				."' class='txt1'>$varName</a></td>\n"
				."<td class='txt1' colspan='10' align='left'>".rglVx($aX,'descr')."</td>\n"
				."<td class='txt1' colspan='6' align='right'>".$sVal."&nbsp;</td>\n"
				."</tr>\n";
		}
		$codX = $acRec['cod_dato'];
		if ($acRec['tipo_tab_dati']==1) {
			$varName = 'B_'.$codX;
		} else {
			$varName = 'Q_'.$codX;
		}
		zzDatiRef($acRec, $aVar, $sCalc);
		return '';
}

function zzDatiRef(&$acRec,&$aVar,&$sCalc) {
	global $objDB,$objSess;
	$sSql = "SELECT dr.cod_dato, d.descr, d.tipo_valore, d.tipo_tab_dati "
		." FROM rgl_def_dato_ref dr"
		." LEFT JOIN rgl_def_dato d ON d.cod_dato = dr.cod_dato "
		."    AND d.id_set_dati = ".$acRec['id_set_dati']
		." WHERE dr.cod_dato_ref = '".$acRec['cod_dato']."' "
		."    AND dr.id_set_dati = ".$acRec['id_set_dati']
		." AND dr.cod_dato <> '".$acRec['cod_dato']."'";
	$objDB->query($sSql,'datoRef');
	if (!$aX = $objDB->fetch('datoRef')) {
		return '';
	}
	$sCalc .= "<tr>\n<td class='lab1' colspan='20' align='center'><b>Referenziato nei seguenti dati</b></td>\n</tr>\n";
	$sCalc .= "<tr>\n"
		."<td class='lab1' colspan='4' align='center'>Nome</td>\n"
		."<td class='lab1' colspan='10' align='center'>Descrizione</td>\n"
		."<td class='lab1' colspan='6' align='center'>Valore</td>\n"
		."</tr>\n";
	while($aX) {
		$codX = $aX['cod_dato'];
		if ($aX['tipo_tab_dati']==1) {
			$varName = 'B_'.$codX;
		} else {
			$varName = 'Q_'.$codX;
		}
		switch($aX['tipo_valore']) {
			case 'euro':
				$sVal = number_format((double)rglVx($aVar,$varName),2,',','.');
				break;
			case 'num':
				$sVal = number_format((double)rglVx($aVar,$varName),0,',','.');
				break;
			case 'perc':
				$sVal = number_format((double)rglVx($aVar,$varName),3,',','.')."%";
				break;
			default:
				$sVal = rglVx($aVar,$varName);
		}	
		$sCalc .= "<tr>\n"
			."<td class='txt1' colspan='4' align='left'>"
			."<a href='calcDato.php?cd=$codX&bil1=".reqVar('bil1')."&bil2=".reqVar('bil2')."&xsn=".XSN
			."' class='txt1'>$varName</a></td>\n"
			."<td class='txt1' colspan='10' align='left'>".rglVx($aX,'descr')."</td>\n"
			."<td class='txt1' colspan='6' align='right'>".$sVal."&nbsp;</td>\n"
			."</tr>\n";
		$aX = $objDB->fetch('datoRef');
	}
	return '';
}
	